package cn.springboot.erp.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.springboot.erp.commons.ResponseResult;
import io.swagger.annotations.Api;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("code")
@Api(tags = "验证码")
public class CaptChaController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("getCode")
    public ResponseResult getCode(){
        // 创建验证码对象
        LineCaptcha lineCaptcha = new LineCaptcha(150, 40, 4, 10);
        // 获取验证码
        String code = lineCaptcha.getCode();
        // 创建"uuid"，"uuid"作为key，"code"作为value缓存到redis
        String uuid = IdUtil.simpleUUID();
        stringRedisTemplate.opsForValue().set(uuid,code,3, TimeUnit.MINUTES);

        // 获取验证码的base64对象
        String imageBase64 = lineCaptcha.getImageBase64();
        // 将"uuid"和"imageBase64返回前端
        return ResponseResult.Success()
                .data("uuid",uuid)
                .data("imageBase64",imageBase64);
    }
}
